/*
 * JuridicalPersonInfoTopComponent.java
 * 
 * Created: Jul 10, 2015
 * 
 * Copyright (c) ExpertPB 2015
 * All information contained herein is, and remains the property of
 * ExpertPB and its suppliers, if any.
 */
package com.emex.app.stuff.juridic;

import com.emex.app.shared.data.Car;
import com.emex.app.stuff.security.SecurityManager;
import com.emex.app.shared.data.JuridicalPerson;
import com.emex.app.shared.data.Numbers;
import com.emex.app.shared.data.OrderPayment;
import com.emex.app.shared.data.OrderPosition;
import com.emex.app.shared.data.Orders;
import com.emex.app.shared.data.User;
import com.emex.app.shared.data.enums.PayMethod;
import com.emex.app.stuff.constant.ReportName;
import com.emex.app.stuff.gui.OrderDialog;
import com.emex.app.stuff.gui.SelectClientDialog;
import com.emex.app.stuff.gui.model.OrdersTableModel;
import com.emex.app.stuff.provider.AuthenticationDataProvider;
import com.emex.app.stuff.provider.CarDataProvider;
import com.emex.app.stuff.provider.ClientDataProvider;
import com.emex.app.stuff.provider.CompanyInfoDataProvider;
import com.emex.app.stuff.provider.JuridicalPersonDataProvider;
import com.emex.app.stuff.provider.OrderDataProvider;
import com.emex.app.stuff.utils.DateUtils;
import com.emex.app.stuff.utils.MoneyToString;
import com.emex.app.stuff.utils.ReportGenerator;
import com.emex.app.stuff.utils.StringUtilities;
import com.emex.app.stuff.utils.UIUtils;
import java.awt.Frame;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRMapArrayDataSource;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Exceptions;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//com.emex.app.stuff.juridic//JuridicalPersonInfo//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "JuridicalPersonInfoTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_NEVER
)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.emex.app.stuff.juridic.JuridicalPersonInfoTopComponent")
@ActionReference(path = "Menu/Юридические лица" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_JuridicalPersonInfoAction",
        preferredID = "JuridicalPersonInfoTopComponent"
)
@Messages({
    "CTL_JuridicalPersonInfoAction=Заказы по юр.лицам",
    "CTL_JuridicalPersonInfoTopComponent=Заказы по юр.лицам",
    "HINT_JuridicalPersonInfoTopComponent=Заказы по юр.лицам"
})
public final class JuridicalPersonInfoTopComponent extends TopComponent {

    private Frame mainWindow = WindowManager.getDefault().getMainWindow();
    private JuridicalPerson client;
    private OrdersTableModel ordersTableModel;

    public JuridicalPersonInfoTopComponent() {
        initComponents();
        setName(Bundle.CTL_JuridicalPersonInfoTopComponent());
        setToolTipText(Bundle.HINT_JuridicalPersonInfoTopComponent());

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        staffNameLabel = new javax.swing.JLabel();
        buttonsPanel = new javax.swing.JPanel();
        addOrderButton = new javax.swing.JButton();
        editOrderButton = new javax.swing.JButton();
        deleteOrderButton = new javax.swing.JButton();
        printButton = new javax.swing.JButton();
        printSchetButton = new javax.swing.JButton();
        searchPanel1 = new javax.swing.JPanel();
        searchTextField1 = new javax.swing.JTextField();
        searchButton1 = new javax.swing.JButton();
        addNewClientButton1 = new javax.swing.JButton();
        orderPositionSearchPanel = new javax.swing.JPanel();
        orderPositionNameField = new javax.swing.JTextField();
        searchOPButton = new javax.swing.JButton();
        staffInfoScrollPanel = new javax.swing.JScrollPane();
        staffInfoPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        bankField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        consigneeField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        phonesField = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        emailField = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        addressTextArea = new javax.swing.JTextArea();
        ordersTableScroll = new javax.swing.JScrollPane();
        ordersTable = new org.jdesktop.swingx.JXTable();

        org.openide.awt.Mnemonics.setLocalizedText(staffNameLabel, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.staffNameLabel.text")); // NOI18N

        buttonsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        addOrderButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/add.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(addOrderButton, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.addOrderButton.text")); // NOI18N
        addOrderButton.setEnabled(false);
        addOrderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addOrderButtonActionPerformed(evt);
            }
        });

        editOrderButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/edit.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(editOrderButton, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.editOrderButton.text")); // NOI18N
        editOrderButton.setEnabled(false);
        editOrderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editOrderButtonActionPerformed(evt);
            }
        });

        deleteOrderButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/delete.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(deleteOrderButton, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.deleteOrderButton.text")); // NOI18N
        deleteOrderButton.setEnabled(false);
        deleteOrderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteOrderButtonActionPerformed(evt);
            }
        });

        printButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/print.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(printButton, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.printButton.text")); // NOI18N
        printButton.setEnabled(false);
        printButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printButtonActionPerformed(evt);
            }
        });

        printSchetButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/print.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(printSchetButton, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.printSchetButton.text")); // NOI18N
        printSchetButton.setEnabled(false);
        printSchetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printSchetButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout buttonsPanelLayout = new javax.swing.GroupLayout(buttonsPanel);
        buttonsPanel.setLayout(buttonsPanelLayout);
        buttonsPanelLayout.setHorizontalGroup(
            buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(addOrderButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(editOrderButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(deleteOrderButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(printButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(printSchetButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        buttonsPanelLayout.setVerticalGroup(
            buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addOrderButton)
                    .addComponent(deleteOrderButton)
                    .addComponent(editOrderButton)
                    .addComponent(printButton)
                    .addComponent(printSchetButton))
                .addContainerGap())
        );

        searchPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.searchPanel1.border.title"))); // NOI18N

        searchTextField1.setText(org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.searchTextField1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(searchButton1, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.searchButton1.text")); // NOI18N
        searchButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButton1ActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(addNewClientButton1, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.addNewClientButton1.text")); // NOI18N
        addNewClientButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addNewClientButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout searchPanel1Layout = new javax.swing.GroupLayout(searchPanel1);
        searchPanel1.setLayout(searchPanel1Layout);
        searchPanel1Layout.setHorizontalGroup(
            searchPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(searchPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(searchTextField1)
                    .addGroup(searchPanel1Layout.createSequentialGroup()
                        .addComponent(searchButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(addNewClientButton1)
                        .addGap(0, 13, Short.MAX_VALUE)))
                .addContainerGap())
        );
        searchPanel1Layout.setVerticalGroup(
            searchPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(searchTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(searchPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchButton1)
                    .addComponent(addNewClientButton1))
                .addContainerGap())
        );

        orderPositionSearchPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.orderPositionSearchPanel.border.title"))); // NOI18N
        orderPositionSearchPanel.setToolTipText(org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.orderPositionSearchPanel.toolTipText")); // NOI18N

        orderPositionNameField.setText(org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.orderPositionNameField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(searchOPButton, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.searchOPButton.text")); // NOI18N
        searchOPButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchOPButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout orderPositionSearchPanelLayout = new javax.swing.GroupLayout(orderPositionSearchPanel);
        orderPositionSearchPanel.setLayout(orderPositionSearchPanelLayout);
        orderPositionSearchPanelLayout.setHorizontalGroup(
            orderPositionSearchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(orderPositionSearchPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(orderPositionNameField)
                .addContainerGap())
            .addGroup(orderPositionSearchPanelLayout.createSequentialGroup()
                .addGap(77, 77, 77)
                .addComponent(searchOPButton)
                .addContainerGap(99, Short.MAX_VALUE))
        );
        orderPositionSearchPanelLayout.setVerticalGroup(
            orderPositionSearchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(orderPositionSearchPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(orderPositionNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(searchOPButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        staffInfoScrollPanel.setBorder(null);

        staffInfoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.staffInfoPanel.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.jLabel1.text")); // NOI18N

        nameTextField.setEditable(false);
        nameTextField.setText(org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.nameTextField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.jLabel2.text")); // NOI18N

        bankField.setEditable(false);
        bankField.setText(org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.bankField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.jLabel3.text")); // NOI18N

        consigneeField.setEditable(false);
        consigneeField.setText(org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.consigneeField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.jLabel4.text")); // NOI18N

        phonesField.setEditable(false);
        phonesField.setText(org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.phonesField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel6, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.jLabel6.text")); // NOI18N

        emailField.setEditable(false);
        emailField.setText(org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.emailField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel7, org.openide.util.NbBundle.getMessage(JuridicalPersonInfoTopComponent.class, "JuridicalPersonInfoTopComponent.jLabel7.text")); // NOI18N

        addressTextArea.setColumns(20);
        addressTextArea.setRows(5);
        addressTextArea.setEnabled(false);
        jScrollPane2.setViewportView(addressTextArea);

        javax.swing.GroupLayout staffInfoPanelLayout = new javax.swing.GroupLayout(staffInfoPanel);
        staffInfoPanel.setLayout(staffInfoPanelLayout);
        staffInfoPanelLayout.setHorizontalGroup(
            staffInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(staffInfoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(staffInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(staffInfoPanelLayout.createSequentialGroup()
                        .addGroup(staffInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7))
                        .addGap(141, 141, 141))
                    .addGroup(staffInfoPanelLayout.createSequentialGroup()
                        .addGroup(staffInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nameTextField)
                            .addComponent(bankField)
                            .addComponent(consigneeField)
                            .addComponent(phonesField)
                            .addComponent(emailField)
                            .addComponent(jScrollPane2))
                        .addContainerGap())))
        );
        staffInfoPanelLayout.setVerticalGroup(
            staffInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(staffInfoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bankField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(consigneeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(phonesField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(emailField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(101, 101, 101))
        );

        staffInfoScrollPanel.setViewportView(staffInfoPanel);

        ordersTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ordersTableMouseClicked(evt);
            }
        });
        ordersTableScroll.setViewportView(ordersTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(staffNameLabel, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(buttonsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(ordersTableScroll))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(orderPositionSearchPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(searchPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(staffInfoScrollPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(staffNameLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(searchPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(orderPositionSearchPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(11, 11, 11)
                        .addComponent(staffInfoScrollPanel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(buttonsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(ordersTableScroll)))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void addOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addOrderButtonActionPerformed
        OrderDialog dialog = new OrderDialog(mainWindow, true);
        dialog.setOrdersTableModel(ordersTableModel);
        dialog.setJuridicalPerson(client);
        dialog.setOrder(null);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);

    }//GEN-LAST:event_addOrderButtonActionPerformed

    private void editOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editOrderButtonActionPerformed
        OrderDialog dialog = new OrderDialog(mainWindow, true);
        dialog.setTitle("Редактирование/Просмотр заказа");
        dialog.setOrdersTableModel(ordersTableModel);
        dialog.setJuridicalPerson(client);
        dialog.setOrder(getOrderSelection());
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }//GEN-LAST:event_editOrderButtonActionPerformed

    private void deleteOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteOrderButtonActionPerformed
        if (!SecurityManager.getDefault().getCurrentPerson().getIsAdmin()) {
            UIUtils.notifyOperationNotAllowed();
            return;
        }

        Orders selection = getOrderSelection();
        ordersTableModel.dataRemoved(selection);
        OrderDataProvider.getInstance().deleteOrderPrimaryKey(selection.getId());
    }//GEN-LAST:event_deleteOrderButtonActionPerformed

    private void printButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printButtonActionPerformed
        Orders selection = getOrderSelection();
        if (null != selection) {
            try {
                HashMap parameters = new HashMap();
                boolean isAvtozavod = true;
                String template;
                if (isAvtozavod) {
                    BufferedImage image = ImageIO.read(getClass().getClassLoader().getResource("body.jpg"));
                    BufferedImage logo = ImageIO.read(getClass().getClassLoader().getResource("logo_avtoz.jpg"));
                    parameters.put("logo", logo);
                    parameters.put("logo_address", image);
                    template = ReportName.ORDER_REPORT_DUB_AVTOZ;
                } else {
                    BufferedImage image = ImageIO.read(getClass().getClassLoader().getResource("emexLogo.jpg"));
                    parameters.put("logo", image);
                    template = ReportName.ORDER_REPORT_DUB;
                }
                parameters.put("orderDate", DateUtils.getExtendedFormattedString(
                        selection.getDate()));
                parameters.put("clientFullFIO", client.getName());
                parameters.put("phone", client.getPhone());
                parameters.put("car", "------------------------");
                parameters.put("VIN", "------------------------");
                parameters.put("car_year", "------------------------");

                User manager = AuthenticationDataProvider.getInstance().selectUserByPrimaryKey(selection.getManagerId());
                if (null == manager) {
                    manager = SecurityManager.getDefault().getCurrentPerson();
                }
                String managerFio = manager.getSurname() + " "
                        + manager.getName() + " "
                        + manager.getPatronymic();

                parameters.put("managerFullFIO", managerFio);
                List<Map<String, String>> tableData = new ArrayList<>();
                List<OrderPosition> orderPositions = OrderDataProvider.getInstance()
                        .getOrderPositionByOrderId(selection.getId());
                Double genSumma = 0.0;
                for (OrderPosition op : orderPositions) {
                    Map<String, String> ordPosInfo = new HashMap<>();
                    ordPosInfo.put("orderPositionName", op.getName());
                    ordPosInfo.put("amount", op.getAmount().toString());
                    ordPosInfo.put("price", op.getPrice().toString());
                    Double result = op.getPrice() * op.getAmount();
                    genSumma += result;
                    ordPosInfo.put("summa", result.toString());
                    tableData.add(ordPosInfo);
                }
                List<OrderPayment> orderPayments = OrderDataProvider.getInstance()
                        .getOrderPaymentByOrderId(selection.getId());
                Double paySum = 0.0;
                for (OrderPayment op : orderPayments) {
                    paySum += op.getSumma();
                }
                parameters.put("genSumma", genSumma.toString());
                parameters.put("prepay", paySum.toString());
                Double ost = genSumma - paySum;
                parameters.put("ostatok", ost.toString());
                Map<String, String>[] tableDS = tableData.toArray(new HashMap[tableData.size()]);
                JRMapArrayDataSource mapDS = new JRMapArrayDataSource(tableDS);
                parameters.put("datasource", new JREmptyDataSource());
                parameters.put("dataSource", mapDS);

                List<Map<String, String>> tableData2 = new ArrayList<>();
                for (OrderPosition op : orderPositions) {
                    Map<String, String> ordPosInfo = new HashMap<>();
                    ordPosInfo.put("orderPositionName2", op.getName());
                    ordPosInfo.put("amount2", op.getAmount().toString());
                    ordPosInfo.put("price2", op.getPrice().toString());
                    Double result = op.getPrice() * op.getAmount();
                    ordPosInfo.put("summa2", result.toString());
                    tableData2.add(ordPosInfo);
                }
                Map<String, String>[] tableDS2 = tableData2.toArray(new HashMap[tableData2.size()]);
                JRMapArrayDataSource mapDS2 = new JRMapArrayDataSource(tableDS2);
                parameters.put("dataSource2", mapDS2);
                JasperPrint jp = ReportGenerator.getInstance().generateReport(parameters, template);
                ReportGenerator.getInstance().showReport(jp);
            } catch (Exception ex) {
                Exceptions.printStackTrace(ex);
                UIUtils.showErrorMessage("Произошли ошибки при печати бланка заказа.");
            }
        }
    }//GEN-LAST:event_printButtonActionPerformed

    private void searchButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButton1ActionPerformed
        if (null != searchTextField1.getText()
                && !searchTextField1.getText().isEmpty()) {
            List<JuridicalPerson> foundClient = JuridicalPersonDataProvider.getInstance().
                    getAllJuridicalPeronsByName(searchTextField1.getText());

            if (foundClient.isEmpty()) {
                UIUtils.showInfoMessage("Клиентов с заданными данными нет в базе");
            } else if (foundClient.size() == 1) {
                this.client = foundClient.get(0);
            } else {
                // Clients more than 1 - show table to choose correct one
                SearchJuridicPersonDialog dialog = new SearchJuridicPersonDialog(mainWindow, true, foundClient);
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
                client = dialog.getClient();
            }

            clientChanged();
        }
    }//GEN-LAST:event_searchButton1ActionPerformed

    private void addNewClientButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addNewClientButton1ActionPerformed
        JuridicalPersonDialog dialog = new JuridicalPersonDialog(mainWindow, true);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
        this.client = dialog.getJuridicalPerson();
        clientChanged();
    }//GEN-LAST:event_addNewClientButton1ActionPerformed

    private void searchOPButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchOPButtonActionPerformed
        if (null != orderPositionNameField.getText()
                && !orderPositionNameField.getText().isEmpty()) {
            List<JuridicalPerson> foundClient = ClientDataProvider.getInstance().
                    getAllJuridicalClientsByOrderPositionName(orderPositionNameField.getText());

            if (foundClient.isEmpty()) {
                UIUtils.showInfoMessage("По заданному названию позиции ничего не найдено");
            } else if (foundClient.size() == 1) {
                this.client = foundClient.get(0);
            } else {
                // Clients more than 1 - show table to choose correct one
                SearchJuridicPersonDialog dialog = new SearchJuridicPersonDialog(mainWindow, true, foundClient);
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
                client = dialog.getClient();
            }

            clientChanged();
        }
    }//GEN-LAST:event_searchOPButtonActionPerformed

    private void ordersTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ordersTableMouseClicked
        if (evt.getClickCount() == 2) {
            editOrderButtonActionPerformed(null);
        }
    }//GEN-LAST:event_ordersTableMouseClicked

    private void printSchetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printSchetButtonActionPerformed
        AskSchetInfoDialog dialog = new AskSchetInfoDialog(mainWindow, true);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
        ReportGenerator.getInstance().showReport(generateInvoiceReport());
        ReportGenerator.getInstance().showReport(generateNakladnaya(dialog.getNumber(), dialog.getDate()));
    }//GEN-LAST:event_printSchetButtonActionPerformed

    @Override
    public void componentOpened() {
        searchPanel1.getRootPane().setDefaultButton(searchButton1);
        ordersTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int row = ordersTable.getSelectedRow();
                if ((row >= 0) && (row < ordersTable.getRowCount())) {
                    editOrderButton.setEnabled(true);
                    deleteOrderButton.setEnabled(true);
                    printButton.setEnabled(true);
                    printSchetButton.setEnabled(true);
                } else {
                    editOrderButton.setEnabled(false);
                    deleteOrderButton.setEnabled(false);
                    printButton.setEnabled(false);
                    printSchetButton.setEnabled(false);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addNewClientButton1;
    private javax.swing.JButton addOrderButton;
    private javax.swing.JTextArea addressTextArea;
    private javax.swing.JTextField bankField;
    private javax.swing.JPanel buttonsPanel;
    private javax.swing.JTextField consigneeField;
    private javax.swing.JButton deleteOrderButton;
    private javax.swing.JButton editOrderButton;
    private javax.swing.JTextField emailField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JTextField orderPositionNameField;
    private javax.swing.JPanel orderPositionSearchPanel;
    private org.jdesktop.swingx.JXTable ordersTable;
    private javax.swing.JScrollPane ordersTableScroll;
    private javax.swing.JTextField phonesField;
    private javax.swing.JButton printButton;
    private javax.swing.JButton printSchetButton;
    private javax.swing.JButton searchButton1;
    private javax.swing.JButton searchOPButton;
    private javax.swing.JPanel searchPanel1;
    private javax.swing.JTextField searchTextField1;
    private javax.swing.JPanel staffInfoPanel;
    private javax.swing.JScrollPane staffInfoScrollPanel;
    private javax.swing.JLabel staffNameLabel;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    private void clientChanged() {
        if (null != client) {
            addOrderButton.setEnabled(true);
            nameTextField.setText(client.getName());
            bankField.setText(client.getBank());
            consigneeField.setText(client.getConsignee());
            phonesField.setText(client.getPhone());
            emailField.setText(client.getEmail());
            addressTextArea.setText(client.getAddress());

            staffNameLabel.setText("Информация о заказах: " + client.getName());
            List<Orders> orders = OrderDataProvider.getInstance().getAllJuridicalClientOrders(client.getId());
            ordersTableModel = new OrdersTableModel(orders);
            ordersTable.setModel(ordersTableModel);

        } else if (null == client) {
            addOrderButton.setEnabled(false);
        }
    }

    protected Orders getOrderSelection() {
        if (ordersTable.getSelectedRow() > -1) {
            Orders orders = (Orders) ordersTable
                    .getValueAt(ordersTable.getSelectedRow(), -1);
            return orders;
        }
        return null;
    }

    protected OrderPayment getOrderPaymentSelection() {
        if (ordersTable.getSelectedRow() > -1) {
            OrderPayment op = (OrderPayment) ordersTable
                    .getValueAt(ordersTable.getSelectedRow(), -1);
            return op;
        }
        return null;
    }

    private JasperPrint generateInvoiceReport() {
        Orders selectedOrder = getOrderSelection();
        JasperPrint incoiceReport = null;
        if (null != selectedOrder) {
            List<OrderPosition> positions = OrderDataProvider.getInstance().
                    getOrderPositionByOrderId(selectedOrder.getId());
            JuridicalPerson seller = JuridicalPersonDataProvider.getInstance().selectJuridicalPersonByPrimaryKey(
                    CompanyInfoDataProvider.getInstance().getCompanyInfo().getJurPersonId());
            Numbers numbers = CompanyInfoDataProvider.getInstance().getNumbers();
            if (numbers == null) {
                numbers = new Numbers();
                numbers.setSchetFactNum(Long.valueOf("0"));
                numbers.setNaklNum(Long.valueOf("0"));
                numbers.setSchetNum(Long.valueOf("0"));
                numbers = CompanyInfoDataProvider.getInstance().insertNumbers(numbers);
            }
            // 1. Формируем счет фактуру
            Map<String, Object> params = new HashMap<>();
            Long num = numbers.getSchetFactNum();
            num++;
            numbers.setSchetFactNum(num);
            numbers = CompanyInfoDataProvider.getInstance().updateNumbers(numbers);
            params.put("number", num.toString());
            params.put("date", DateUtils.getFormatedDateString(new Date()));
            params.put("seller", StringUtilities.getSellerJurPersonDescription(seller));
            params.put("buyer", StringUtilities.getBuyerJurPersonDescription(client));
            params.put("documentPassport", StringUtilities.getIPPassport(seller));
            List<Map<String, String>> tableData = new ArrayList<>();
            Double genSumma = 0.0;
            for (OrderPosition op : positions) {
                Map<String, String> item = new HashMap<>();
                genSumma += (op.getAmount() * op.getPrice());
                item.put("field1", op.getName());
                item.put("field2", "");
                item.put("field3", "1");
                item.put("field4", op.getAmount().toString());
                item.put("field5", op.getPrice().toString().endsWith(".0") ? op.getPrice().toString() + "0" : op.getPrice().toString());
                item.put("field6", op.getPrice().toString().endsWith(".0") ? op.getPrice().toString() + "0" : op.getPrice().toString());
                item.put("field7", "без акциза");
                item.put("field8", "без НДС");
                item.put("field9", "без НДС");
                item.put("field10", op.getPrice().toString().endsWith(".0") ? op.getPrice().toString() + "0" : op.getPrice().toString());
                item.put("field11", "-");
                item.put("field12", "-");
                item.put("field13", "-");
                tableData.add(item);
            }
            params.put("genSumma", genSumma.toString().endsWith(".0") ? genSumma.toString() + "0" : genSumma.toString());
            Map<String, String>[] tableDS = tableData.toArray(new HashMap[tableData.size()]);
            JRMapArrayDataSource mapDS = new JRMapArrayDataSource(tableDS);
            params.put("datasource", new JREmptyDataSource());
            params.put("positionsDataSource", mapDS);

            try {
                incoiceReport = ReportGenerator.getInstance().generateReport(params, ReportName.INVOICE_REPORT);
            } catch (JRException ex) {
                ex.printStackTrace();
                UIUtils.showErrorMessage("Произошли ошибки при печати счет-фактуры");
            }
        }
        return incoiceReport;
    }

    private JasperPrint generateNakladnaya(String schetNum, Date date) {
        Orders selectedOrder = getOrderSelection();
        JasperPrint nakl = null;
        if (null != selectedOrder) {
            List<OrderPosition> positions = OrderDataProvider.getInstance().
                    getOrderPositionByOrderId(selectedOrder.getId());
            JuridicalPerson seller = JuridicalPersonDataProvider.getInstance().selectJuridicalPersonByPrimaryKey(
                    CompanyInfoDataProvider.getInstance().getCompanyInfo().getJurPersonId());
            Numbers numbers = CompanyInfoDataProvider.getInstance().getNumbers();
            Map<String, Object> params = new HashMap<>();
            Long naklNum = numbers.getNaklNum();
            naklNum++;
            numbers.setNaklNum(naklNum);
            CompanyInfoDataProvider.getInstance().updateNumbers(numbers);
            StringBuilder b = new StringBuilder();
            b.append("Продавец: ").append(seller.getName()).append("\n");
            b.append("Покупатель: ").append(client.getName()).append("\n");
            b.append("Через кого: ").append("\n");
            b.append("Основание: По счету № ").append(schetNum).append(" от ").append(DateUtils.getFormatedDateString(date));
            params.put("title", "НАКЛАДНАЯ № " + naklNum + " от " + DateUtils.getFormatedDateString(new Date()));
            params.put("seller", b.toString());
            params.put("recordOne", "Отпустил________________________");
            params.put("recordTwo", "Получил_________________________");
            Double genSumma = 0.0;
            Integer genAmount = 0;
            List<Map<String, String>> td = new ArrayList<>();
            Integer posNum = 1;
            for (OrderPosition op : positions) {
                Map<String, String> item = new HashMap<>();
                genAmount += op.getAmount();
                genSumma += (op.getAmount() * op.getPrice());
                item.put("field1", posNum.toString());
                item.put("field2", op.getName());
                item.put("field3", "1");
                item.put("field4", op.getAmount().toString());
                item.put("field5", op.getPrice().toString().endsWith(".0") ? op.getPrice().toString() + "0" : op.getPrice().toString());
                Double sum = op.getAmount() * op.getPrice();
                item.put("field6", sum.toString().endsWith(".0") ? sum.toString() + "0" : sum.toString());
                td.add(item);
                ++posNum;
            }
            Map<String, String>[] tds = td.toArray(new HashMap[td.size()]);
            JRMapArrayDataSource ds = new JRMapArrayDataSource(tds);
            params.put("positionsDataSource", ds);
            params.put("genAmount", genAmount.toString());
            params.put("genSumma", genSumma.toString().endsWith(".0") ? genSumma.toString() + "0" : genSumma.toString());
            params.put("sumInWords", "Cумма прописью: " + new MoneyToString().convert(genSumma));
            params.put("datasource", new JREmptyDataSource());

            try {
                nakl = ReportGenerator.getInstance().generateReport(params, ReportName.NAKLADNAYA);
            } catch (JRException ex) {
                ex.printStackTrace();
                UIUtils.showErrorMessage("Произошли ошибки при печати накладной");
            }
        }
        return nakl;
    }
}
